package com.ruoyi.web.controller;

import cn.hutool.core.io.FileUtil;
import com.ruoyi.common.constant.CommonConstants;
import com.ruoyi.framework.config.AliossConfig;
import com.ruoyi.framework.redis.CacheTool;
import com.ruoyi.framework.utils.FileDyUtils;
import com.ruoyi.framework.utils.ServerUtils;
import com.ruoyi.framework.web.controller.BaseController;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.StringUtil;
import net.dreamlu.mica.launch.MicaProperties;
import net.dreamlu.mica.props.MicaUploadProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用接口
 *
 * @author dyun
 */
@Slf4j
@RestController
@RequestMapping("openapi/common")
@AllArgsConstructor
public class CommonController extends BaseController {

    private final MicaProperties micaProperties;

    private final MicaUploadProperties micaUploadProperties;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileDyUtils.isValidFilename(fileName)) {
                throw new Exception(StringUtil.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + FileDyUtils.getRealDownloadFileName(fileName);
            String filePath = FileDyUtils.getFileDownloadPath(fileName);

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileDyUtils.setFileDownloadHeader(request, realFileName));
            FileUtil.writeToStream(filePath, response.getOutputStream());
            if (delete) {
                FileUtil.del(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @SneakyThrows
    @PostMapping("/upload")
    public R uploadFile(MultipartFile file) {
        Map<String, Object> ajax = new HashMap<>(16);
        String url;

        // 三个部分：文件保存路径，新增文件路径规则，文件名称
        String savaPath = micaUploadProperties.getSavePath();
        String uploadPath = FileDyUtils.getUploadPath();
        String fileName = FileDyUtils.renameFile(file.getOriginalFilename());

        if (AliossConfig.ossClient != null) {
            // 1、优先oss保存。
            url = AliossConfig.upload(file, uploadPath + fileName);
        } else {
            // 2、本地保存。生成上传文件路径， 上传并返回新文件名称
            FileUtil.mkdir(savaPath + uploadPath);
            file.transferTo(FileUtil.file(savaPath + uploadPath + fileName));

            // 返回名称及路径， 其中域名部分（默认用户定义的域名地址，如果未设置，则自动配置）
            url = micaProperties.get(CommonConstants.SERVER_DOMAIN, ServerUtils.getServerDomain())
                    + micaUploadProperties.getUploadPathPattern().replace("/**", "") + uploadPath + fileName;
        }

        ajax.put("fileName", fileName);
        ajax.put("url", url);
        return success(ajax);
    }

    /**
     * 获取alioss上传密钥
     */
    @GetMapping("/upload/policy")
    public R getPolicy() {
        if (AliossConfig.ossClient != null) {
            return success(CacheTool.getPolicy());
        }
        return success();
    }

}
